<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-01 18:08:00
 * @Description  : 用户登录页面
-->

<template>
  <Login-box>
    <n-form
      ref="userLoginFormRef"
      label-placement="left"
      label-width="auto"
      :model="userLoginForm"
      :rules="userLoginFormRules"
      size="medium"
      class="flex flex-col items-center"
    >
      <n-form-item path="username" class="w-[300px]">
        <n-input
          v-model:value="userLoginForm.username"
          placeholder="请输入用户名"
          :maxlength="50"
          clearable
          :allow-input="noSideSpace"
        >
          <template #prefix>
            <n-icon :component="User" />
          </template>
        </n-input>
      </n-form-item>
      <n-form-item path="password" class="w-[300px]">
        <n-input
          v-model:value="userLoginForm.password"
          placeholder="请输入密码"
          type="password"
          show-password-on="click"
          :maxlength="20"
          :allow-input="noSideSpace"
        >
          <template #prefix>
            <n-icon :component="Key" />
          </template>
        </n-input>
      </n-form-item>
      <div class="flex justify-between w-[300px] pb-[10px] items-center">
        <n-checkbox v-model:checked="rememberMe"> 记住密码 </n-checkbox>
        <n-button
          quaternary
          type="info"
          class="text-right"
          @click="handleToFindPwd"
        >
          忘记密码
        </n-button>
      </div>
      <n-form-item class="w-[300px]">
        <n-button type="primary" @click="handleLogin" class="w-[300px]">
          登录
        </n-button>
      </n-form-item>
    </n-form>
    <!-- <n-divider title-placement="center" class="m-0">
      <n-tag round class="text-gray-400">更多登录方式</n-tag>
    </n-divider>
    <div class="login-methods flex justify-center items-center pt-[10px]">
      <n-space class="items-center">
        <svg-icon
          icon="QQ"
          color="#199ae3"
          size="24px"
          class="cursor-pointer"
        />
        <svg-icon
          icon="weixin"
          color="#18a058"
          size="24px"
          class="cursor-pointer"
        />
        <svg-icon
          icon="github-fill"
          color="#000"
          size="24px"
          class="cursor-pointer"
        />
      </n-space>
    </div> -->
    <n-button quaternary type="info" @click="handleToRegister">
      立即注册
    </n-button>
  </Login-box>
</template>

<script setup lang="ts">
import { useMessage } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { User, Key } from '@vicons/fa'
import { errRouter } from '@/router'
import useUserStore from '@/stores/modules/user'
import { userLogin } from '@/api/user'
import { IS_REMEBER, LOGIN_REMEBER } from '@/constants/user'
import { noSideSpace } from '@/utils'
import { load } from '@/utils/loading'
import { getItem, removeItem, setItem } from '@/utils/storage'
import aes from '@/utils/aes'
import { userSchema } from '@/utils/rule'
import LoginBox from './LoginBox.vue'

const message = useMessage()
const router = useRouter()
const userStore = useUserStore()

const emits = defineEmits<{
  (e: 'changeCurModel', value: 'register' | 'login' | 'findPwd'): void
}>()

// ------------------用户登录相关逻辑---------------------
const userLoginForm = reactive({
  username: '',
  password: ''
})

const userLoginFormRules = reactive({
  username: userSchema.username,
  password: userSchema.password
})

const userLoginFormRef = ref<FormInst | null>(null)

const rememberMe = ref(false) // 是否记住密码

// 登录
const handleLogin = () => {
  userLoginFormRef.value?.validate((errors) => {
    if (!errors) {
      if (rememberMe) {
        setItem(LOGIN_REMEBER, {
          // 保存用户名和密码
          username: aes.encrypt(userLoginForm.username),
          password: aes.encrypt(userLoginForm.password)
        })
      } else {
        removeItem(LOGIN_REMEBER)
      }
      load.show()
      // 进行登录
      userLogin({
        username: userLoginForm.username,
        password: userLoginForm.password
      })
        .then((res) => {
          message.success('登录成功')
          userStore.setToken(res.data)
          if (!userStore.userInfo) {
            userStore.getUserInfo()
          }
          if (userStore.isLoadRoute) {
            router.push({
              name: 'home'
            })
          } else {
            // 进行动态路由的添加
            userStore
              .setAsyncRoutes()
              .then((asyncRoutes: any) => {
                router.addRoute(asyncRoutes[0])
                router.addRoute(errRouter)
                // console.log(router.getRoutes())
              })
              .finally(() => {
                router.push({
                  name: 'home'
                })
              })
          }
        })
        .catch(console.error)
        .finally(() => {
          load.hide()
        })
    } else {
      console.log(errors)
      message.error('填写信息有误')
    }
  })
}

// 调整到注册
const handleToRegister = () => {
  emits('changeCurModel', 'register')
}

// 跳转到找回密码
const handleToFindPwd = () => {
  emits('changeCurModel', 'findPwd')
}

// 如果存在保存的用户名和密码，进行回显
const loadLoginRemeber = () => {
  const info = getItem(LOGIN_REMEBER)
  if (info) {
    userLoginForm.username = aes.decrypt(info.username) || ''
    userLoginForm.password = aes.decrypt(info.password) || ''
  }
}

// 获取是否记住密码标识
const getIsRemeber = () => {
  const isRemeber = getItem(IS_REMEBER)
  rememberMe.value = isRemeber + '' === 'true' ? true : false
}

onMounted(() => {
  getIsRemeber()
  loadLoginRemeber()
})

// 保存是否记住密码标识
const saveIsReember = () => {
  setItem(IS_REMEBER, '' + rememberMe.value)
  if (!rememberMe.value) {
    removeItem(LOGIN_REMEBER)
  }
}
onUnmounted(() => {
  saveIsReember()
})
</script>

<style scoped lang="scss"></style>
